package vn.ugame.module.store;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import vn.ugame.model.bl.StoreService;
import vn.ugame.model.entity.Image;
import vn.ugame.module.AbstractModule;
import vn.ugame.module.ActionConfig;
import vn.ugame.module.Module;
import vn.ugame.module.Param;

public class ImageModule extends AbstractModule implements Module {

    public ImageModule()
    {
    }

    @ActionConfig(urlPattern = {"^(?<itemId>\\w+)/(?<type>\\d+)$"})
    public void returnImage(@Param("itemId") String itemId, @Param("type") int type) 
            throws ServletException, IOException {
        //Declare service
        StoreService service = new StoreService();
        
       //Find item image
        List<Image> images = null;
        try {
            images = service.findImage(itemId, type);
        } catch (Exception ex) {
            ex.printStackTrace();
            getResponse().setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
        
        if(images.isEmpty()){
            getResponse().setStatus(HttpServletResponse.SC_NOT_FOUND);
        }

        //Get real path of item image
        String fileName = getContext().getRealPath(images.get(0).getPath());
        //Get mine type of the image
        String mimeType = getContext().getMimeType(fileName);
        //Process mine type of image not found
        if (mimeType == null) {
            getResponse().setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
        //Set content type
        getResponse().setContentType(mimeType);
        //Set content size
        File file = new File(fileName);
        getResponse().setContentLength((int) file.length());
        //Set header
        getResponse().setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
        //Open the file and output streams
        FileInputStream in = new FileInputStream(file);
        OutputStream out = getResponse().getOutputStream();
        //Copy the contents of the file to the output stream
        byte[] buf = new byte[1024];
        int count = 0;
        while ((count = in.read(buf)) >= 0) {
            out.write(buf, 0, count);
        }
        //Close all streams
        in.close();
        out.close();
    }
}
